'use client';

import type { TBody, TMetadata } from '@/types';
import { type ReactNode, useEffect, useState } from 'react';
import classNames from 'classnames';
import type { IPostFollowsMessage } from '@/interfaces';
import { useMutation, useQuery } from '@tanstack/react-query';
import useToast from '@/hooks/useToast';
import {
  postCancelFollow,
  postFollowRead,
  queryPostFollowMessage,
  removeFollow,
} from '@/services/api';
import { toRelativeTime } from '@/lib/tool';
import ErrorPage from '@/app/[locale]/error/error';
import LoadPage from '@/app/[locale]/load/load';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';
import useUser from '@/hooks/useUser';
import Link from 'next/link';

export default function FollowH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <Follow metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const Follow = ({ metadata }: { metadata: TMetadata }) => {
  const userQuery = useUser(metadata);
  const { show } = useToast();
  const [currentReadFollowMessageId, setCurrentReadFollowMessageId] =
    useState<number>();
  const [currentRemoveFollowMessageId, setCurrentRemoveFollowMessageId] =
    useState<number>();
  const [pages, setPages] = useState<IPostFollowsMessage[]>(
    metadata.all['follow'].v as IPostFollowsMessage[],
  );

  const queryPostFollowMessageQuery = useQuery(
    metadata.all['follow'].k,
    async () => {
      return (await queryPostFollowMessage()) as IPostFollowsMessage[];
    },
    {
      enabled: !!(userQuery.data && userQuery.data.user),
      initialData: metadata.all['follow'].v as IPostFollowsMessage[],
    },
  );

  const postFollowReadMutation = useMutation(async (variables: TBody<void>) => {
    await postFollowRead(variables);
  });
  const cancelFollowMutation = useMutation(async (variables: TBody<void>) => {
    await postCancelFollow(variables);
  });
  const removeFollowMutation = useMutation(async (variables: TBody<void>) => {
    await removeFollow(variables);
  });

  useEffect(() => {
    if (queryPostFollowMessageQuery.data) {
      setPages(
        queryPostFollowMessageQuery.data.map((item) => {
          item._contentUpdatedOn = toRelativeTime(item.contentUpdatedOn);
          return item;
        }),
      );
    }
  }, [queryPostFollowMessageQuery.data]);

  async function onClickCancel(item: IPostFollowsMessage, index: number) {
    try {
      setCurrentRemoveFollowMessageId(item.id);

      await Promise.all([
        cancelFollowMutation.mutateAsync({ id: item.postId + '' }),
        removeFollowMutation.mutateAsync({
          id: item.postId + '',
        }),
      ]);

      setPages((prevState) => {
        prevState.splice(index, 1);
        return prevState;
      });

      show({
        type: 'SUCCESS',
        message: '取消关注完成',
      });
    } catch (e) {
      cancelFollowMutation.reset();
      removeFollowMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setCurrentRemoveFollowMessageId(undefined);
    }
  }

  async function onClickRead(item: IPostFollowsMessage) {
    try {
      setCurrentReadFollowMessageId(item.id);

      await postFollowReadMutation.mutateAsync({
        id: item.id + '',
      });
      await queryPostFollowMessageQuery.refetch({ throwOnError: true });

      show({
        type: 'SUCCESS',
        message: '已读完成',
      });
    } catch (e) {
      postFollowReadMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setCurrentReadFollowMessageId(undefined);
    }
  }

  if (queryPostFollowMessageQuery.data) {
    if (pages.length > 0) {
      return (
        <div className="col p-2">
          <div className="card rounded-5 border-0">
            <div className="card-body yw-bg">
              {pages.map((item, index) => {
                return (
                  <div
                    key={item.id}
                    className="row z-1"
                    style={{ marginBottom: -2 }}
                  >
                    <div className="col-auto px-0 mx-0">
                      <div className="d-flex flex-column align-items-center h-100">
                        <Circle className="yw-bg">
                          <Circle width={32} height={32} className="yw-bg">
                            <i className="bi bi-bell-fill fs-5 text-primary"></i>
                          </Circle>
                        </Circle>
                        <Line className="yw-bg" />
                      </div>
                    </div>
                    <div className="col-auto px-0 mx-0">
                      <Line reverse className="yw-bg" />
                    </div>
                    <div className="col p-2 pb-3">
                      <div className="card border-0">
                        <div className="card-body vstack gap-4">
                          <h5 className="card-title">
                            <Link
                              className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
                              href={`/posts/${item.postId}`}
                            >
                              {item.name}
                            </Link>
                          </h5>
                          <div>
                            <Link
                              className="btn btn-primary"
                              href={`/posts/${item.postId}`}
                            >
                              <i className="bi bi-book me-2"></i>
                              阅读更多
                            </Link>
                          </div>
                        </div>
                        <div className="card-footer">
                          <div className="d-flex align-items-center justify-content-between">
                            <div>{item._contentUpdatedOn}</div>
                            <div className="hstack gap-2">
                              <button
                                disabled={
                                  currentRemoveFollowMessageId === item.id
                                }
                                onClick={onClickCancel.bind(this, item, index)}
                                type="button"
                                className="btn focus-ring focus-ring-danger text-danger btn-sm"
                              >
                                {currentRemoveFollowMessageId === item.id && (
                                  <span
                                    className="spinner-border spinner-border-sm me-2"
                                    role="status"
                                    aria-hidden="true"
                                  ></span>
                                )}
                                取消关注
                              </button>

                              <button
                                disabled={
                                  currentReadFollowMessageId === item.id
                                }
                                onClick={onClickRead.bind(this, item)}
                                type="button"
                                className="btn focus-ring focus-ring-primary text-primary btn-sm"
                              >
                                {currentReadFollowMessageId === item.id && (
                                  <span
                                    className="spinner-border spinner-border-sm me-2"
                                    role="status"
                                    aria-hidden="true"
                                  ></span>
                                )}
                                已读
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="col p-2">
        <div className="card rounded-5 border-0">
          <div className="card-body py-4">
            <Nodata />
          </div>
        </div>
      </div>
    );
  }

  if (queryPostFollowMessageQuery.error) {
    return <ErrorPage error={queryPostFollowMessageQuery.error} />;
  }

  return <LoadPage />;
};

const Circle = ({
  width,
  height,
  children,
  className,
}: {
  width?: number;
  height?: number;
  children?: ReactNode;
  className?: string;
}) => {
  return (
    <div
      className={classNames(
        'rounded-circle border d-flex align-items-center justify-content-center flex-shrink-0',
        className,
      )}
      style={{ width: width ?? 48, height: height ?? 48 }}
    >
      {children && children}
    </div>
  );
};

const Line = ({
  width,
  height,
  className,
  reverse,
}: {
  width?: number;
  height?: number;
  className?: string;
  reverse?: boolean;
}) => {
  return (
    <div
      className={classNames(
        'border',
        className,
        reverse
          ? 'w-100 border-top border-bottom border-start-0 border-end-0'
          : 'h-100 border-start border-end border-top-0 border-bottom-0',
      )}
      style={
        reverse
          ? {
              width: width && width > 0 ? width + 2 : '12px !important',
              height: height ?? 10,
              marginLeft: -2,
              marginTop: '1.2rem',
            }
          : {
              width: width ?? 10,
              marginTop: -2,
            }
      }
    ></div>
  );
};
